import { 
  LOGIN_USER_REQUEST, 
  LOGIN_USER_FAILURE, 
  LOGIN_USER_SUCCESS, 
  LOGOUT_USER, 
  CLEAR_ERROR
} from '../constants';
import CONFIG from '../../config';
import { push } from 'react-router-redux';
import { checkHttpStatus } from '../Helper';

export function loginUserRequest() {
  return { 
    type: LOGIN_USER_REQUEST,
  }
}

export function loginUserFailure(error) {
  localStorage.removeItem('IMLOOKE_COM_USER_TOKEN');
  localStorage.removeItem('IMLOOKE_COM_USER_PHONE');
  localStorage.removeItem('IMLOOKE_COM_USER_USERID');
  return {
    type: LOGIN_USER_FAILURE,
    payload: error
  }
}

export function loginUserSuccess(token, phone, userId) {
  localStorage.setItem('IMLOOKE_COM_USER_TOKEN', token);
  localStorage.setItem('IMLOOKE_COM_USER_PHONE', phone);
  localStorage.setItem('IMLOOKE_COM_USER_USERID', userId);
  return {
    type: LOGIN_USER_SUCCESS,
    payload: {
      token: token,
      phone: phone,
      userId: userId
    }
  }
}

export function login(phone, password, redirect='/i') {
	return (dispatch) => {
		dispatch(loginUserRequest());
		return fetch(CONFIG.apiHost + '/api/login', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({phone: phone, password: password})
    })
    .then(checkHttpStatus)
    .then(res => res.json())
    .then(res => {
      let msg = res.msg;
      dispatch(loginUserSuccess(msg.access_token, msg.phone, msg.user_id));
      dispatch(push(redirect));
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        dispatch(loginUserFailure(v));
      })
    })
	}
}

export function logout() {
  localStorage.removeItem('IMLOOKE_COM_USER_TOKEN');
  localStorage.removeItem('IMLOOKE_COM_USER_PHONE');
  localStorage.removeItem('IMLOOKE_COM_USER_USERID');
  return {
    type: LOGOUT_USER
  }
}

export function logoutAndRedirect(location = '/') {
  return (dispatch, state) => {
    dispatch(logout());
    dispatch(push(location));
  }
}

export function clearError() {
  return {
    type: CLEAR_ERROR
  }
}
